import axios from 'axios'
import store from "../store/index"
import router from "@/router"
import {ElMessage} from 'element-plus'

const errorMap = {
    400: "语义有误",
    401: "服务器认证失败",
    403: "服务器拒绝访问",
    404: "地址错误",
    500: "服务器遇到意外",
    502: "服务器无响应",
}

const instance = axios.create({
    baseURL: store.state.baseUrl,
    // headers: { "Content-Type": "application/json" },
    timeout: 5000
})

instance.interceptors.request.use(
    (config) => {
        const token = store.state.tokens
        token && (config.headers.AuthorizationV = token)
        return config
    },
    (error) => {
        return Promise.reject(error);
    }
)

//响应拦截器
instance.interceptors.response.use(
    (response) => {
        // console.log(response)
        return response.data
    },
    (error) => {
        const {response} = error
        if (response.status === 401) {
            // 清除token
            store.commit('setToken', '')
            // 跳转到登录页面
            router.push('/login');
            ElMessage.error('请先登录')
            return Promise.resolve();
        } else {
            const errorMessage = errorMap[response.status] || response.info
        }
        return Promise.reject(error)
    }
)

export default instance